package notification

import (
	"errors"
	"math/rand"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/oklog/ulid/v2"
)

func NewULID() ulid.ULID {
	t := time.Now()
	entropy := ulid.Monotonic(rand.New(rand.NewSource(t.UnixNano())), 0)
	return ulid.MustNew(ulid.Timestamp(t), entropy)
}

//随机请求hosts其中之一，得到一个通讯成功的应答
func Do(hosts []string, req *http.Request) (*http.Response, error) {
	len := len(hosts)
	if len == 0 {
		return nil, errors.New("no host available")
	}
	n := rand.Intn(len)
	host := hosts[n]
	u, err := url.Parse(strings.TrimSpace(host))
	if err != nil {
		return nil, err
	}
	req.URL.Scheme = u.Scheme
	req.URL.Host = u.Host
	res, err := http.DefaultClient.Do(req)
	if err == nil && res.StatusCode == http.StatusBadGateway {
		err = errors.New(http.StatusText(http.StatusBadGateway))
		if res != nil && res.Body != nil {
			res.Body.Close()
		}
	}
	if err != nil {
		newHosts := append(hosts[:n], hosts[n+1:]...)
		//retry
		return Do(newHosts, req)
	}
	return res, nil
}
